<?php
/**
 * This file is part of manage.
 * Author: FKL
 * Date: 2017/10/25
 * Time: 10:55
 * File: Vcc6017032301Controller.php
 */

namespace Ivr\HttpBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use GuzzleHttp\Client;

/**
 * 瓜子
 * Class Vcc6017032301Controller
 * @package Ivr\HttpBundle\Controller
 */
class Vcc6017032301Controller extends Controller
{
    public $guaziUrl = array(
        '0' => 'http://call.guazi.com/v2/external/call_redirect',
        '1' => 'http://call.guazi.com/test/external/call_redirect',
    );

    /**
     * 瓜子IVR调用接口
     * @param Request $request
     * @return JsonResponse
     */
    public function indexAction(Request $request)
    {
        $istest = $request->get('istest', 0);
        $secret = $request->get('secret', '6YQ26UFP87C8X6BV');
        $phone = $request->get('phone', '');
        $from = $request->get('from', 'zhongtong');

        $timestamp = time();
        $stringToSign = $from.$phone.$timestamp.$secret;
        $signature = md5($stringToSign);

        try {
            $tokenUrl = $this->guaziUrl[$istest];
            $client = new Client(array('timeout' => 5.0));
            $response = $client->request(
                'POST',
                $tokenUrl,
                array(
                    'form_params' => array(
                        'phone' => $phone,
                        'from' => $from,
                        'timestamp' => $timestamp,
                        'signature' => $signature,
                        ),
                    )
            );
            $content = $response->getBody()->getContents();
            $data = json_decode($content, true);
            if (json_last_error() !== JSON_ERROR_NONE || !isset($data['business_line'])) {
                $this->get("logger")->error(sprintf("瓜子接口返回错误，参数【%s】，返回值【%s】", $stringToSign, $content));

                return new JsonResponse(array('result' => 'failure'));
            }

            return new JsonResponse(array(
                'result' => 'success',
                'data' => array(
                    'business_line' => $data['business_line'],
                ),
            ));
        } catch (\Exception $e) {
            $this->get("logger")->error(sprintf("瓜子接口访问失败，参数【%s】，报错【%s】", $stringToSign, $e->getMessage()));

            return new JsonResponse(array('result' => 'failure'));
        }
    }
}
